package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //通过用户名称查找用户
        User user = userService.findByUsername(username);
        if (user == null) {
            return null;
        }
        //获取用户拥有的角色
        Set<Role> roles = user.getRoles();

        //创建授权集合
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();

        //遍历用户拥有的角色
        if (roles != null) {
            for (Role role : roles) {
                //用户角色
                authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
                //获取角色拥有的所有权限
                Set<Permission> permissions = role.getPermissions();
                if (permissions != null) {
                    for (Permission permission : permissions) {
                        //用户授权
                        authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }
        //返回框架的user
        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorities);
    }
}
